package controller.ur;

import java.io.IOException;

import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import model.dao.AlbumDaoLocal;
import model.dao.UserDaoLocal;
import model.entity.Album;
import model.entity.User;
import controller.CUtil;

/**
 * Servlet implementation class SCreateAlbumOut
 */
public class SCreateAlbumOut extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	@EJB
	private AlbumDaoLocal albumDao;
	
	@EJB
	private UserDaoLocal userDao;
	
	private Logger log=Logger.getLogger(SCreateAlbumOut.class);
    /**
     * @see HttpServlet#HttpServlet()
     */
    public SCreateAlbumOut() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		if(!CUtil.checkLogIn(request, response))
			return;
		request.setCharacterEncoding("UTF-8");
		
		User user=(User)request.getSession().getAttribute("user");
		String title=(String)request.getParameter("title");
		if(albumDao.titleExists(title)){
			request.setAttribute("message", "Album \""+title+"\" exists. Type new title.");
			CUtil.redirecter(request, response, "SCreateAlbum");
			return;
		}
		String description=(String)request.getParameter("description");
		String[] ispublics=request.getParameterValues("ispublic");
		Boolean ispublic;
		if(ispublics!=null && ispublics.length!=0){
			ispublic=true;
		}else{
			ispublic=false;
		}
		
		Album album=new Album();
		album.setTitle(title);
		album.setDescription(description);
		album.setUser(user);
		album.setPub(ispublic);
		user.getAlbums().add(album);
		albumDao.persist(album);
		userDao.merge(user);
		log.info("Album created: "+album.toString());
		CUtil.lastPageRedirect(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
